package cn.ciis.server.handler;

import cn.ciis.basic.TioHandlerInterface;
import cn.ciis.basic.base.BaseCache;
import cn.ciis.basic.kit.ByteKit;
import cn.ciis.basic.kit.CiisKit;
import cn.ciis.basic.kit.EnumKit;
import cn.ciis.basic.kit.J2CacheKit;
import cn.ciis.basic.model.Dictionary;
import cn.ciis.basic.plugin.CiisHandler;
import cn.ciis.basic.plugin.CiisSessionContext;
import cn.ciis.ciis.dictionary.DictionaryAdminService;
import cn.ciis.server.CiisPacket;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cybermkd.mongo.kit.MongoQuery;
import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备数据
 */
@TioHandlerInterface(order = 2)
public class DeviceDataHandler extends CiisHandler {


    DictionaryAdminService dictionaryAdminService = Aop.get(DictionaryAdminService.class);

    @Override
    public void handle(CiisPacket ciisPacket, CiisSessionContext ciisSessionContext) {
        if( StrUtil.equalsIgnoreCase("5aca",ByteKit.bytesToHexString(ciisPacket.getCmd()))){//判断是否是设备数据
            LogKit.info("接收到客户端发送过来的信息:{}",ByteKit.bytesToHexString(ciisPacket.getBody()));
            MongoQuery mongoQuery = new MongoQuery();

            byte[] body=ciisPacket.getBody();
            byte[][] bytes = ArrayUtil.split(body, 2);//拆分数组

            //传感器类型缓存
            List<Dictionary> dictionary= (List<Dictionary>) J2CacheKit.get(BaseCache.EQUIPMENT_DATA_DICTIONARY,"01", s -> {
                return  dictionaryAdminService.findByPid(1);
            }).getValue();

            //设备可以接收的数据类型
            char[] validates = null;
            if(StrKit.isBlank(ciisSessionContext.getEquipment().get().getValidity())){
                validates = new char[0];
            }else{
                validates = ciisSessionContext.getEquipment().get().getValidity().toCharArray();
            }

            int min = NumberUtil.min(bytes.length, dictionary.size(), validates.length);
            JSONObject json = new JSONObject();
            Map<String,Object> sensor = MapUtil.newHashMap();
            json.put("enterprise_code",ciisSessionContext.getEnterprise().get().getCode() );
            json.put("equipment_code", ciisSessionContext.getEquipment().get().getCode());
            double res =0.0;
            StrBuilder builder = null;
            for (int i = 0; i < min; i++) {
                if(validates[i] == 49){
                    res = converAndCalc(bytes[i]);
                    json.put(dictionary.get(i).getField(),res);
                    builder=builder.create();
                    builder.append(res);
                    builder.append(" | ");
                    if(i < ciisSessionContext.getEquipment().get().getSensorArray().length){
                        if(ciisSessionContext.getEquipment().get().getSensorArray()[i] == '1'){
                            builder.append("在线");
                        }else{
                            builder.append("离线");
                        }
                    }else{
                        builder.append("离线");
                    }
                    sensor.put(dictionary.get(i).getName(), builder.toString());
                }
            }
            ciisSessionContext.getEquipment().get().put("now_data", sensor);//将传感器数据缓存到会话中
            json.put("create_time", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            LogKit.info("保存到MongoDB的数据是:{}",json);
            boolean save = mongoQuery.use(EnumKit.MongoCollect.devices_data_info.toString()).set(json).save();
            if(!save){
                LogKit.error("MongoDB保存设备数据信息失败。");
            }
            reply(ciisSessionContext,ciisPacket);
        }else{
            goNext(ciisPacket,ciisSessionContext);
        }
    }

    public double converAndCalc(byte[] bytes){
        int anInt = Integer.parseInt(ByteKit.bytesToHexString(bytes), 16);

        double num = NumberUtil.div(anInt,100,2);
        LogKit.info("转换结果:{}",num);
        return num;
    }

    /**
     * 回复客户端信息
     * @param ciisSessionContext
     */
    public void reply(CiisSessionContext ciisSessionContext,CiisPacket ciisPacket){
        ciisPacket.setBody(ByteKit.hexStr2Bytes(ByteKit.DecToHexString(0,2)));
        CiisKit.sendMsg(ciisSessionContext,ciisPacket);
    }
}
